<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%" top="5vh">
    <el-form
      v-loading="formLoading"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      class="pb-50px"
      @submit.prevent
    >
      <!-- 自我介绍 -->
      <el-form-item prop="selfIntroduction" :label="t('candidate.applyDialog.selfIntroduction')">
        <el-input
          v-model="formData.selfIntroduction"
          type="textarea"
          :placeholder="
            t('common.inputTextPlaceholder') + t('candidate.applyDialog.selfIntroduction')
          "
          :disabled="!isEdit"
          :autosize="{ minRows: 4, maxRows: 10 }"
          :maxlength="500"
          resize="none"
          show-word-limit
          clearable
        />
      </el-form-item>
      <!-- 发表论文情况 -->
      <el-form-item
        prop="paperIds"
        :label="t('candidate.applyDialog.paper')"
        :style="{ marginBottom: !isEdit ? 0 : 18 }"
      >
        <el-select
          v-if="isEdit"
          v-model="formData.paperIds"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.applyDialog.paper')"
          multiple
          collapse-tags
          clearable
        >
          <el-option
            v-for="item in paperList"
            :key="item.id"
            :label="item.paperTitle"
            :value="item.id"
            :disabled="item.publicationStatus === '已接收'"
          />
        </el-select>
      </el-form-item>
      <!-- 预览 -->
      <SelectedPaperTable v-if="selectedPaperList.length || !isEdit" :list="selectedPaperList" />
      <div v-if="!isEdit" style="height: 20px"></div>
      <!-- 专利情况 -->
      <el-form-item
        prop="patentIds"
        :label="t('candidate.applyDialog.patent')"
        :style="{ marginBottom: !isEdit ? 0 : 18 }"
      >
        <el-select
          v-if="isEdit"
          v-model="formData.patentIds"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.applyDialog.patent')"
          multiple
          collapse-tags
          clearable
        >
          <el-option
            v-for="item in patentList"
            :key="item.id"
            :label="item.patentName"
            :value="item.id"
            :disabled="patentDisabled(item)"
          />
        </el-select>
      </el-form-item>
      <!-- 预览 -->
      <SelectedPatentTable v-if="selectedPatentList.length || !isEdit" :list="selectedPatentList" />
      <div v-if="!isEdit" style="height: 20px"></div>
      <!-- 申请材料 -->
      <el-form-item prop="attachment" :label="t('candidate.applyDialog.attachment')">
        <IMRUpload
          v-model="formData.attachment"
          :file-type="['pdf']"
          :file-size="2"
          :limit="1"
          :disabled="!isEdit"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        v-if="isEdit"
        @click="saveDraft"
        type="warning"
        :loading="saveLoading"
        :disabled="formLoading || saveLoading"
        >{{ t('candidate.applyDialog.saveDraft') }}</el-button
      >
      <el-button
        v-if="isEdit"
        @click="submitForm"
        type="primary"
        :loading="formLoading"
        :disabled="formLoading || saveLoading"
        >{{ t('candidate.operate.apply') }}</el-button
      >
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
  <Dialog title="提醒" v-model="awardAlert" :fullscreen="false" :show-close="false" top="3vh">
    <div class="award-alert">
      <p style="text-indent: 0 !important">本人郑重承诺：</p>
      <h1>一、所提交的申请材料均不涉密；</h1>
      <h1
        >二、已如实填报科研成果信息，以共同第一作者身份发表的科研成果均已明确写明本人排序，其中，共同第一作者排名第一的科研成果已如实填报；</h1
      >
      <h1>三、科研成果署名均符合下列要求：</h1>
      <p>1.论文为已发表（含在线可查），专利为已授权；</p>
      <p
        >2.本人署名身份为第一作者、共同第一作者或除导师外第一作者（导师以中国科大研究生综合服务平台登记为准，联合培养研究生以金属研究所研究生业务平台为准）；</p
      >
      <h1>四、科研成果取得时间符合下列要求：</h1>
      <p>1.取得中国科学技术大学材料科学与工程学院学籍后（联合培养研究生为正式入所后）；</p>
      <p>2.已毕业申请者的科研成果截止申请日且与学位论文相关；</p>
      <h1>五、本次申报的所有科研成果，在之前的评选中从未获得过本奖项；</h1>
      <h1
        >六、完全知晓并自愿承担因材料不实或违规申报导致的参评资格取消等后果，如有违反学术诚信行为，自愿接受相关处分及处罚。</h1
      >
    </div>
    <template #footer>
      <el-button type="primary" @click="confirmAlert()" :disabled="countdown > 0">
        确认<span v-if="countdown > 0">({{ countdown }})</span>
      </el-button>
      <el-button @click="cancelAlert()">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {
  AwardApplicationApi,
  AwardApplyDTO,
  AwardVO,
  CandidateExtendInfoVO
} from '@/api/awards/candidate'
import { StudentPatentApi, StudentPatentVO } from '@/api/core/studentpatent'
import { StudentPaperApi, StudentPaperVO } from '@/api/core/studentpaper'
import { useCache } from '@/hooks/web/useCache'
import { FormRules } from 'element-plus'
import IMRUpload from '@/components/IMRUpload/index.vue'
import SelectedPaperTable from '@/views/awards/candidate/components/SelectedPaperTable.vue'
import SelectedPatentTable from '@/views/awards/candidate/components/SelectedPatentTable.vue'

defineOptions({ name: 'ApplicationAwards' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref() // 表单 Ref
const isEdit = ref(false)
const formLoading = ref(false)
const saveLoading = ref(false)
const paperList = ref<StudentPaperVO[]>([]) // 论文列表的数据
const patentList = ref<StudentPatentVO[]>([]) // 专利列表的数据
const candidateExtendInfo = ref<CandidateExtendInfoVO>()

const selectedPaperList = computed(() => {
  return paperList.value.filter((item) => formData.value.paperIds.includes(item.id))
})

const selectedPatentList = computed(() => {
  return patentList.value.filter((item) => formData.value.patentIds.includes(item.id))
})

const formData = ref<AwardApplyDTO>({
  selfIntroduction: '',
  attachment: '[]',
  instanceId: '',
  paperIds: [],
  patentIds: []
})

const formRules = reactive<FormRules>({
  selfIntroduction: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('candidate.applyDialog.selfIntroduction'),
      trigger: 'blur'
    }
  ]
})

const allowedPatentRanks = ['本人第一', '导师第一，本人第二'] // 允许选择的专利个人排名条件
function patentDisabled(item: StudentPatentVO) {
  return !(item.patentStatus === '已授权' && allowedPatentRanks.includes(item.personalRanking))
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

// 暂存
const saveDraft = async () => {
  await formRef.value.validate()
  saveLoading.value = true
  try {
    await AwardApplicationApi.saveDraft(formData.value)
    message.success(t('candidate.applyDialog.saveSuccess'))
    dialogVisible.value = false
    emit('success')
  } finally {
    saveLoading.value = false
  }
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  try {
    await showAwardAlert()
    // 提交请求
    formLoading.value = true
    await AwardApplicationApi.applyAward(formData.value)
    message.success(t('common.applySuccess'))
    dialogVisible.value = false
    candidateExtendInfo.value = undefined
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    selfIntroduction: '',
    attachment: '[]',
    instanceId: '',
    paperIds: [],
    patentIds: []
  }
  formRef.value?.resetFields()
}

// 自动设置自我介绍
const autoSetIntroduction = async () => {
  if (formData.value.selfIntroduction) {
    return
  }
  if (candidateExtendInfo.value?.selfIntroduction) {
    formData.value.selfIntroduction = candidateExtendInfo.value.selfIntroduction
    return
  }
  try {
    const res = await AwardApplicationApi.getCandidateExtendInfo()
    if (res && res.selfIntroduction) {
      formData.value.selfIntroduction = res.selfIntroduction
      candidateExtendInfo.value = res
    }
  } catch {}
}

// 打开弹窗
const open = async (row: AwardVO, edit = false) => {
  resetForm()
  dialogTitle.value = row.awardsName
  formData.value.instanceId = row.instanceId
  isEdit.value = edit
  dialogVisible.value = true

  formLoading.value = true
  // 查一下最新的数据
  await initData()
  if (!edit || row.status === -1) {
    await getApplyDetail(row.candidateId)
  }
  if (edit) {
    await autoSetIntroduction()
  }
  formLoading.value = false
}

// 获取申请详情
const getApplyDetail = async (id: string) => {
  try {
    const res = await AwardApplicationApi.getAwardApplyDetail(id)
    formData.value.selfIntroduction = res.selfIntroduction ?? ''
    formData.value.attachment = res.attachment ?? '[]'
    if (res.studentPaperUseList.length) {
      formData.value.paperIds = res.studentPaperUseList.map((item: any) => item.paperId)
    }
    if (res.studentPatentUseList.length) {
      formData.value.patentIds = res.studentPatentUseList.map((item: any) => item.patentId)
    }
  } catch {}
}

// ========== 提示 ===========

const { wsCache } = useCache()
// 评奖强提醒
const awardAlert = ref(false)
// 评奖强提醒倒计时
const countdown = ref(10)
// 评奖倒计时走字
const startCountdown = () => {
  // 如果countdown的值不为0 则每秒-1 直到归零停止
  if (countdown.value > 0) {
    setTimeout(() => {
      countdown.value--
      startCountdown()
    }, 1000)
  }
}
// 评奖强提醒确定
let awardResolve: any
// 评奖强提醒取消
let awardReject: any

// 显示第一个评奖强提醒
const showAwardAlert = () => {
  return new Promise((resolve, reject) => {
    const flag: boolean = wsCache.get('awards-mentor-tips')
    // 显示第一个弹窗
    awardAlert.value = true
    // 倒计时20秒
    countdown.value = flag ? 0 : 10
    // 开始及时
    startCountdown()
    // 保存resolve和reject给外面使用
    awardResolve = resolve
    awardReject = reject
  })
}

// 确认提醒
const confirmAlert = () => {
  awardAlert.value = false
  awardResolve?.()
  countdown.value = 0
  // 保存已经确认过的状态
  wsCache.set('awards-mentor-tips', true, {
    // 缓存1天
    exp: 86400
  })
}

// 取消强提醒
const cancelAlert = () => {
  awardAlert.value = false
  awardReject?.()
  countdown.value = 0
}

//====================

// 初始化数据
const initData = async () => {
  try {
    const patentRes = await StudentPatentApi.getStudentPatentPage({ pageNo: 1, pageSize: 9999 })
    patentList.value = patentRes.list
  } catch {}
  try {
    const paperRes = await StudentPaperApi.getStudentPaperPage({ pageNo: 1, pageSize: 9999 })
    paperList.value = paperRes.list
  } catch {}
}

onMounted(async () => {
  formLoading.value = true
  await initData()
  formLoading.value = false
})

defineExpose({
  open
})
</script>

<style scoped lang="scss">
.award-alert {
  line-height: 32px;
  text-indent: 2em;

  p {
    font-size: 16px;
  }

  h1 {
    font-size: 16px;
    margin-top: 10px;
  }
}
</style>
